﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Modules.System.User;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Exceptions;
using static Modules.System.Flow.FlowConstants;

namespace Modules.System.Flow
{
    [UseDI(ServiceLifetime.Scoped)]
    public class SysFlowEngineService
    {
        private readonly SysFlowEngineRepository sysFlowEngineRepository;
        private readonly IApplicationContext applicationContext;
        private readonly ILogger logger;

        public SysFlowEngineService(SysFlowEngineRepository sysFlowEngineRepository,
            IApplicationContext applicationContext,
            ILogger<UserService> logger
            )
        {
            this.sysFlowEngineRepository = sysFlowEngineRepository;
            this.applicationContext = applicationContext;
            this.logger = logger;
        }

        public IEnumerable<SysFlowEngine> GetFlowEnginesByFlowIds(List<int> flowIds)
        {
            return sysFlowEngineRepository.GetFlowEnginesByFlowIds(flowIds);
        }

        public void InsertSysFlowEngine(SysFlowEngine sysFlowEngine)
        {
            sysFlowEngineRepository.Insert(sysFlowEngine);
        }

        public IEnumerable<SysFlowEngine> GetSysFlowEngineByFlowId(int flowId)
        {
            return sysFlowEngineRepository.GetSysFlowEngineByFlowId(flowId);
        }

        /// <summary>
        /// 查询当前流程第一步
        /// </summary>
        /// <param name="flowId"></param>
        /// <returns></returns>
        public SysFlowEngine? GetFirstFlowEngine(int flowId)
        {
            var sysFlowEngines = sysFlowEngineRepository.GetSysFlowEngineByFlowId(flowId);
            if (sysFlowEngines == null)
                return null;
            return sysFlowEngines.FirstOrDefault();
        }

        public SysFlowEngine? GetFlowEngineByFlowEngineCode(int flowId, FlowEngine flowEngineCode)
        {
            var sysFlowEngines = sysFlowEngineRepository.GetSysFlowEngineByFlowId(flowId);
            if (sysFlowEngines == null)
                return null;
            return sysFlowEngines.Where(a => a.Code == flowEngineCode).FirstOrDefault();
        }

        /// <summary>
        /// 查询当前流程最后一步
        /// </summary>
        /// <param name="flowId"></param>
        /// <returns></returns>
        public SysFlowEngine? GetLastFlowEngine(int flowId)
        {
            var sysFlowEngines = sysFlowEngineRepository.GetSysFlowEngineByFlowId(flowId);
            if (sysFlowEngines == null)
                return null;
            return sysFlowEngines.LastOrDefault();
        }

        /// <summary>
        /// 查询当前流程下一步
        /// </summary>
        /// <param name="flowId">流程id</param>
        /// <param name="flowEngineId">步骤id</param>
        /// <returns></returns>
        public SysFlowEngine? GetNextFlowEngine(int flowId, FlowEngine flowEngineCode)
        {
            var sysFlowEngines = sysFlowEngineRepository.GetSysFlowEngineByFlowId(flowId);
            if (sysFlowEngines == null)
                return null;
            SysFlowEngine? sysFlowEngine = sysFlowEngines.Where(a => a.Code == flowEngineCode).FirstOrDefault();
            sysFlowEngines = sysFlowEngines.Where(a => a.Sort > sysFlowEngine.Sort);
            return sysFlowEngines.FirstOrDefault();
        }

        /// <summary>
        /// 查询当前流程上一步
        /// </summary>
        /// <param name="flowId">流程id</param>
        /// <param name="flowEngineId">步骤id</param>
        /// <returns></returns>
        public SysFlowEngine? GetPreviousFlowEngine(int flowId, FlowEngine flowEngineCode)
        {
            var sysFlowEngines = sysFlowEngineRepository.GetSysFlowEngineByFlowId(flowId);
            if (sysFlowEngines == null)
                return null;
            SysFlowEngine? sysFlowEngine = sysFlowEngines.Where(a => a.Code == flowEngineCode).FirstOrDefault();
            sysFlowEngines = sysFlowEngines.Where(a => a.Sort < sysFlowEngine.Sort);
            return sysFlowEngines.LastOrDefault();
        }

        public void InsertSysFlowEngines(int flowId, IEnumerable<SysFlowEngine> sysFlowEngines)
        {
            try
            {
                applicationContext.Transaction.Begin();//开始事务
                int sort = 1;
                var datas = sysFlowEngineRepository.GetSysFlowEngineByFlowId(flowId);
                foreach (var item in datas)
                {
                    sysFlowEngineRepository.Delete(item);
                }
                foreach (var item in sysFlowEngines)
                {
                    item.FlowId = flowId;
                    item.Sort = sort;
                    item.CreateTime = DateTime.Now;
                    sysFlowEngineRepository.Insert(item);
                    sort++;
                }
                applicationContext.Transaction.Complete();//完成事务
            }
            catch (Exception ex)
            {
                applicationContext.Transaction.Abort();//回滚事务
                logger.LogError(ex, $"CreateUser Exception code:{flowId}");
                throw new BusinessException("写入用户数据失败");
            }
        }
    }
}